//
//  RecordListViewController.m
//  MoneyLog
//
//  Created by wicresoft on 5/31/11.
//  Copyright 2011 wicresoft. All rights reserved.
//

#import "RecordListViewController.h"
#import "RecordViewController.h"
#import "GlobalDef.h"
#import "RecordListSettingViewCotroller.h"

#import "RecordWrapper.h"
#import "RecordCell.h"

extern NSString *kSectionTitleKey;
extern NSString *kRowItemKey;

@implementation RecordListViewController
@synthesize dataSourceArray;
@synthesize dataView;
@synthesize _tableView;

@synthesize searchDate,searchMode;

@synthesize lastAnimation;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [dataSourceArray release];
    [dataView release];
    [backItem release];
    [editButton release];
    [addButton release];
    [doneButton release];
    [flexSpace release];
    [segmentedButton release];
    
    [_tableView release];
    [searchDate release];
    
    [lastAnimation release];
    [settingController release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self._tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    self._tableView.rowHeight = ROW_HEIGHT;

    dataSourceArray = [[NSMutableArray alloc] initWithCapacity:1];
    
    appRect=[[UIScreen mainScreen] applicationFrame];
    backItem=[[UIBarButtonItem alloc] 
              initWithTitle:@"返回" 
              style:UIBarButtonItemStyleBordered 
              target:nil 
              action:nil];
    
    //edit button
    editButton = [[UIBarButtonItem alloc] 
                  initWithBarButtonSystemItem:UIBarButtonSystemItemEdit 
                  target:self 
                  action:@selector(editAction)];
    addButton = [[UIBarButtonItem alloc] 
                 initWithBarButtonSystemItem:UIBarButtonSystemItemAdd 
                 target:self 
                 action:@selector(addAction)];
    self.navigationItem.rightBarButtonItem = addButton;
    
    doneButton = [[UIBarButtonItem alloc] 
                  initWithBarButtonSystemItem:UIBarButtonSystemItemDone 
                  target:self 
                  action:@selector(doneAction)];
    
    flexSpace = [[UIBarButtonItem alloc] 
                 initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace 
                 target:self action:nil];
    
    UISegmentedControl *segmentedControl =[[UISegmentedControl alloc] initWithFrame:CGRectMake(50, 0, 100, 28)];
    segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;
    [segmentedControl insertSegmentWithImage:[UIImage imageNamed:@"Icon_up.png"] atIndex:0 animated:YES];
    [segmentedControl insertSegmentWithImage:[UIImage imageNamed:@"Icon_down.png"] atIndex:1 animated:YES];
    [segmentedControl addTarget:self action:@selector(segmentedAction:) forControlEvents:UIControlEventValueChanged];
    segmentedControl.momentary = YES;

    segmentedButton =[[UIBarButtonItem alloc] initWithCustomView:segmentedControl];
    [segmentedControl release];

    //创建筛选按钮
//    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 28)];//allocate titleView
//    UISegmentedControl  *segmented =[[UISegmentedControl alloc] initWithFrame:CGRectMake(50, 0, 100, 28)];
//    segmented.segmentedControlStyle = UISegmentedControlStyleBar;
//    [segmented insertSegmentWithImage:[UIImage imageNamed:@"Icon_up.png"] atIndex:0 animated:YES];
//    [segmented insertSegmentWithImage:[UIImage imageNamed:@"Icon_down.png"] atIndex:1 animated:YES];
//    [segmented addTarget:self action:@selector(segmentedAction:) forControlEvents:UIControlEventValueChanged];
//    segmented.momentary = YES;
//    [titleView addSubview:segmented];
//    [segmented release];
//    
//    self.navigationItem.titleView=titleView;
//    [titleView release];
    

    
//    self.searchDisplayController.searchBar.autocorrectionType = UITextAutocorrectionTypeNo;
//	  self.searchDisplayController.searchBar.autocapitalizationType = UITextAutocapitalizationTypeNone;
//    self.searchDisplayController.searchBar.scopeButtonTitles = dataSourceArray;

    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
	NSDateComponents *dateComponents = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:searchDate];
	year = [dateComponents year];
    month = [dateComponents month];
	day = [dateComponents day];
    [calendar release];
    
    //self.navigationController.toolbarHidden = NO;
    self.navigationController.toolbar.barStyle =UIBarStyleDefault;
    
    settingController= [[RecordListSettingViewCotroller alloc] init];
    
    lastDisplayType= 0;
    settingController.displayType = lastDisplayType;
    
    settingController.searchType = searchMode;
    lastSearchType = searchMode;
    settingController.view.hidden= YES;
    
    [self.view addSubview:dataView];
    [self.view addSubview:settingController.view];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self.navigationController setToolbarHidden:NO animated:YES];
    UIBarButtonItem *sortItem =[[UIBarButtonItem alloc]
                                initWithBarButtonSystemItem:UIBarButtonSystemItemPageCurl
                                target:self 
                                action:@selector(sortAction:)];
    
    NSArray *barItems = [NSArray arrayWithObjects:editButton,flexSpace,segmentedButton,flexSpace,sortItem, nil];
    self.toolbarItems = barItems;
    
    [self loadData:-1];
    if (![self.searchDisplayController isActive]) {
        self._tableView.tableHeaderView = nil;
    }
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
   
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.navigationController setToolbarHidden:YES animated:YES];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    //return (interfaceOrientation == UIInterfaceOrientationPortrait);
    return YES;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
	[self commitAnimation];
}


-(void)setEditing:(BOOL)editing animated:(BOOL)animated
{
    [self._tableView beginUpdates];
    [self._tableView setEditing:editing animated:YES];
    [self._tableView endUpdates];
    
    [super setEditing:editing animated:animated];
}

#pragma mark - * Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    //#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return [dataSourceArray count];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    NSString *title=@"";
    
    if ([self.dataSourceArray count]!= 1) {
        title = [[self.dataSourceArray objectAtIndex:section] objectForKey:kSectionTitleKey];
    }
    
    return title;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //#warning Incomplete method implementation.
    // Return the number of rows in the section.
    NSMutableArray *array = [[self.dataSourceArray objectAtIndex:section] objectForKey:kRowItemKey];
    return [array count]; 
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"RecordCell";
    
    RecordCell *recordCell = (RecordCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (recordCell == nil) {
        recordCell = [[[RecordCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    
    recordCell.frame = CGRectMake(0.0, 0.0, appRect.size.width, ROW_HEIGHT);
	recordCell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    NSMutableArray *array = [[self.dataSourceArray objectAtIndex:indexPath.section] objectForKey:kRowItemKey];
    [recordCell setRecordWrapper:[array objectAtIndex:indexPath.row]];
    
    return recordCell;
}

// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSArray *array = [[self.dataSourceArray objectAtIndex:indexPath.section] objectForKey:kRowItemKey];
    if(indexPath.row >= [array count])
    {
        return UITableViewCellEditingStyleInsert;
    }    
    else
    {
        return UITableViewCellEditingStyleDelete;
    }
}

// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSMutableArray *array = [[self.dataSourceArray objectAtIndex:indexPath.section] objectForKey:kRowItemKey];
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        RecordWrapper *record = [array objectAtIndex:indexPath.row];
        if ( [g_Database recordDelete:record.id] ) {
            [array removeObjectAtIndex:indexPath.row];
            [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
        }
        else {
            
            UIAlertView *alertView = [[UIAlertView alloc] 
                                      initWithTitle:@"提示"
                                      message:@"删除失败了" 
                                      delegate:nil 
                                      cancelButtonTitle:@"OK" 
                                      otherButtonTitles:nil, nil];
            [alertView show];
            [alertView release];
        }
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
    
}

- (void)tableView:(UITableView *)tableView willBeginEditingRowAtIndexPath:(NSIndexPath *)indexPath
{
	NSLog(@"section: %d, row: %d", indexPath.section, indexPath.row);
}

- (void)tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath
{
	NSLog(@"section: %d, row: %d", indexPath.section, indexPath.row);
}

/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
 {
 }
 */

/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
 {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */

#pragma mark - * Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSMutableArray *array = [[self.dataSourceArray objectAtIndex:indexPath.section] objectForKey:kRowItemKey];
    RecordViewController *controller =[[RecordViewController alloc] initWithStyle:UITableViewStyleGrouped];
    controller.record=[array objectAtIndex:indexPath.row];
    controller.viewMode=1;
    controller.titleString=@"编辑记录";
    
    self.navigationItem.backBarButtonItem =backItem;
    [self.navigationController pushViewController:controller animated:YES];
    [controller release];
    
}

#pragma mark - * UIScrollViewDelegate Methods

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{	
//    [UIView beginAnimations:nil context:nil];
//    backgroundView.frame =CGRectMake(0, -44, appRect.size.width, 0);
//    
//    dateTitleView.hidden = YES;
//    dateTitleView.frame =CGRectMake(0, -44, appRect.size.width, 0);
//    [UIView commitAnimations];
//    
//    dateViewShow = NO;
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    self._tableView.tableHeaderView = self.searchDisplayController.searchBar;
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
}

#pragma mark - * UISearchBarDelegate

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchTerm{
    if([searchTerm length]==0){
        //[self reset];
    }else{
        //searchname=(NSString *)searchTerm;
        //[self searchset];
    }
}

// called when keyboard search button pressed
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
	[searchBar resignFirstResponder];
}

// called when cancel button pressed
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
	[searchBar resignFirstResponder];
    
    [self loadRecord:@""];
    [self._tableView reloadData];
}

- (void)searchBar:(UISearchBar *)searchBar selectedScopeButtonIndexDidChange:(NSInteger)selectedScope
{
    //    searchSelectedScope =selectedScope; 
    
    //    NSString *whereString =[NSString string];
    //    if ([searchBar.text length] != 0) {
    //        whereString = [whereString stringByAppendingFormat:@" (kind like \"%%%@%%\"",searchBar.text];
    //        whereString = [whereString stringByAppendingFormat:@" or sub_kind like \"%%%@%%\"",searchBar.text];
    //        whereString = [whereString stringByAppendingFormat:@" or remark like \"%%%@%%\" )",searchBar.text];
    //        
    //        switch (searchSelectedScope) {
    //            case 0 :
    //                break;
    //            case 1:
    //                whereString =[whereString stringByAppendingString:@" and type='支出'"];
    //                break;
    //            case 2:
    //                whereString =[whereString stringByAppendingString:@" and type='收入'"];
    //                break;
    //            default:
    //                break;
    //        }
    //        
    //        [self loadRecord:whereString];
    //        [self.tableView reloadData];
    //    }
}

#pragma mark - * UISearchDisplayDelegate
- (void)searchDisplayController:(UISearchDisplayController *)controller didLoadSearchResultsTableView:(UITableView *)tableView
{
    tableView.rowHeight = ROW_HEIGHT;
}

- (void)searchDisplayController:(UISearchDisplayController *)controller didShowSearchResultsTableView:(UITableView *)tableView
{
}

- (void)searchDisplayController:(UISearchDisplayController *)controller didHideSearchResultsTableView:(UITableView *)tableView
{
}

- (void)searchDisplayController:(UISearchDisplayController *)controller willUnloadSearchResultsTableView:(UITableView *)tableView
{
    
}

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
    
    NSString *whereString =[NSString string];
    
    whereString = [whereString stringByAppendingFormat:@" (kind like \"%%%@%%\"",searchString];
    whereString = [whereString stringByAppendingFormat:@" or sub_kind like \"%%%@%%\"",searchString];
    whereString = [whereString stringByAppendingFormat:@" or remark like \"%%%@%%\" )",searchString];
    
    //    switch (searchSelectedScope) {
    //        case 0 :
    //            break;
    //        case 1:
    //            whereString =[whereString stringByAppendingString:@" and type='支出'"];
    //            break;
    //        case 2:
    //            whereString =[whereString stringByAppendingString:@" and type='收入'"];
    //            break;
    //        default:
    //            break;
    //    }
    
    [self loadRecord:whereString];
    
//    if ([recordArray count] != 0) {
//        [self._tableView reloadData];
//    }
    
    return YES;
}

#pragma mark - * Action

-(void)editAction{
    
    if (isHalfAnimation) {
        [self commitAnimation];
    }

    [self setEditing:YES animated:YES]; 
    
    UIBarButtonItem *sortItem =[[UIBarButtonItem alloc]
               initWithBarButtonSystemItem:UIBarButtonSystemItemPageCurl
               target:self 
               action:@selector(sortAction:)];
    NSArray *barItems = [NSArray arrayWithObjects:doneButton,flexSpace,segmentedButton,flexSpace,sortItem, nil];
    self.toolbarItems=barItems;
}

-(void)addAction{
    
    if (isHalfAnimation) {
        [self commitAnimation];
    }
    
    RecordViewController *controller =[[RecordViewController alloc] initWithStyle:UITableViewStyleGrouped];
    controller.titleString=@"添加记录";
    controller.viewMode=0;
    controller.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    UINavigationController* navigation = [[UINavigationController alloc] initWithRootViewController:controller];
    navigation.navigationItem.backBarButtonItem = backItem;
    [self.navigationController presentModalViewController:navigation animated:YES];
    [navigation release];
    [controller release];
}

-(void) doneAction
{    
    if (isHalfAnimation) {
        [self commitAnimation];
    }

    UIBarButtonItem *sortItem =[[UIBarButtonItem alloc]
                                initWithBarButtonSystemItem:UIBarButtonSystemItemPageCurl
                                target:self 
                                action:@selector(sortAction:)];
    NSArray *barItems = [NSArray arrayWithObjects:editButton,flexSpace,segmentedButton,flexSpace,sortItem, nil];
    self.toolbarItems=barItems;
    
    [self setEditing:NO animated:YES];  
}

-(void)cancelAction{
    [self setEditing:NO animated:YES];   
}

-(IBAction) segmentedAction: (id) sender
{
    if (isHalfAnimation) {
        [self commitAnimation];
    }
    
    int selectIndex =[sender selectedSegmentIndex];
    [self loadData:selectIndex];
}

-(void) loadRecord:(NSString *) strWhere 
{
    [self.dataSourceArray removeAllObjects];
    NSMutableArray *dataArray =[g_Database getRecordArray:strWhere];
    switch (lastDisplayType) {
        case 0:
        {
            NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                                        dataArray,kRowItemKey,
                                        @"",kSectionTitleKey,nil];
            [self.dataSourceArray addObject:dictionary];
            break;
        }
        case 1:
        {
            NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"datetime" ascending:NO];
            NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
            [dataArray sortUsingDescriptors:sortDescriptors];
            [sortDescriptor release];
            
            for(RecordWrapper *record in dataArray)
            {
                NSString *section=[NSString stringWithFormat:@"%04d-%02d-%02d",record.year,record.month,record.day]; 
                if (searchMode == 2) {
                    section=[NSString stringWithFormat:@"%04d-%02d",record.year,record.month]; 
                }
                
                if ([self.dataSourceArray count]==0) {
                    NSMutableArray *array = [NSMutableArray array];
                    [array addObject:record];
                    
                    NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                                                array,kRowItemKey,
                                                section,kSectionTitleKey,nil];
                    [self.dataSourceArray addObject:dictionary];
                }
                else {
                    NSDictionary *dictionary= [self.dataSourceArray objectAtIndex:[self.dataSourceArray count]-1];
                    NSString *tempSection = [dictionary objectForKey:kSectionTitleKey];
                    if ([section isEqualToString:tempSection]) {
                        NSMutableArray *array = [dictionary objectForKey:kRowItemKey];
                        [array addObject:record];
                    }
                    else {
                        NSMutableArray *array = [NSMutableArray array];
                        [array addObject:record];
                        NSDictionary *newDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                                                    array,kRowItemKey,
                                                    section,kSectionTitleKey,nil];
                        [self.dataSourceArray addObject:newDictionary];
                    }
                }
            }
            
            break;
        }
        case 2:
        {
            NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"type" ascending:NO];
            NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
            [dataArray sortUsingDescriptors:sortDescriptors];
            [sortDescriptor release];
            for(RecordWrapper *record in dataArray)
            {
                NSString *section=record.type;
                                 
                if ([self.dataSourceArray count]==0) {
                    NSMutableArray *array = [NSMutableArray array];
                    [array addObject:record];
                    
                    NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                                                array,kRowItemKey,
                                                section,kSectionTitleKey,nil];
                    [self.dataSourceArray addObject:dictionary];
                }
                else {
                    NSDictionary *dictionary= [self.dataSourceArray objectAtIndex:[self.dataSourceArray count]-1];
                    NSString *tempSection = [dictionary objectForKey:kSectionTitleKey];
                    if ([section isEqualToString:tempSection]) {
                        NSMutableArray *array = [dictionary objectForKey:kRowItemKey];
                        [array addObject:record];
                    }
                    else {
                        NSMutableArray *array = [NSMutableArray array];
                        [array addObject:record];
                        NSDictionary *newDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                                                       array,kRowItemKey,
                                                       section,kSectionTitleKey,nil];
                        [self.dataSourceArray addObject:newDictionary];
                    }
                }
            }
            break;
        }
        default:
            break;
    }
    
    
    [dataArray release];
}

-(void)loadData:(int)selectIndex
{
    NSString *labelText=@"";
    
    if (selectIndex == -1) {
        
        switch (searchMode) {
            case 0:
            {
                //修正从设置页面加载记录时的BUG
                NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
                NSDateComponents *dateComponents = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:searchDate];
                year = [dateComponents year];
                month = [dateComponents month];
                day = [dateComponents day];
                [calendar release];
                
                [self loadRecord:[NSString stringWithFormat:@" year=%d and month=%d and day=%d",year,month,day]];                                
                labelText = [NSString stringWithFormat:@"%04d-%02d-%02d",year,month,day];
                break;
            }
            case 1:
                [self loadRecord:[NSString stringWithFormat:@" year=%d and month=%d",year,month]];
                labelText = [NSString stringWithFormat:@"%04d-%02d",year,month];
                break;
            case 2:
                [self loadRecord:[NSString stringWithFormat:@" year=%d",year]];
                labelText = [NSString stringWithFormat:@"%04d",year];
                break;
            default:
                break;
        }
        
        [self setTitleText:labelText];
        [self._tableView reloadData];
        return;
    }
    
    switch (searchMode) {
        case 0:
        {
            NSDate *newDate=nil;
            NSDateFormatter *dateFormatter =[[NSDateFormatter alloc] init];
            NSTimeInterval timeInterval = selectIndex==0? -24*60*60 : 24*60*60;
            NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
            newDate =[searchDate dateByAddingTimeInterval:timeInterval];
            
            [dateFormatter setDateFormat:@"yyyy-MM-dd"];
            labelText = [dateFormatter stringFromDate:newDate];
            
            NSDateComponents *dateComponents = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:newDate];
            year = [dateComponents year];
            month = [dateComponents month];
            day = [dateComponents day];
            [self loadRecord:[NSString stringWithFormat:@" year=%d and month=%d and day=%d",year,month,day]];
            
            self.searchDate = newDate;
            [dateFormatter release];
            [calendar release];
            break;
        }
        case 1:
        {
            day = 1;
            month =  selectIndex==0? --month : ++month;
            if (month ==0) {
                year--;
                month =12;
            }
            else if(month == 13)
            {
                year++;
                month=1;
            }
            
            labelText = [NSString stringWithFormat:@"%04d-%02d",year,month];
            [self loadRecord:[NSString stringWithFormat:@" year=%d and month=%d",year,month]];
            break;  
        }
        case 2:
            day = 1;
            year = selectIndex==0 ? --year : ++year;
                        
            labelText = [NSString stringWithFormat:@"%04d",year];
            [self loadRecord:[NSString stringWithFormat:@" year=%d",year]];
            break; 
        default:
            break;
    }    
    
    [self setTitleText:labelText];
    [self._tableView reloadData];
}

-(void)sortAction:(id)sender
{
    if (isHalfAnimation) {
        [self commitAnimation];
    }
    else
    {
        [self startAnimation];
    }
    //[self curlUp];
}

-(void)startAnimation{
    CATransition *animation = [CATransition animation];
    animation.delegate = self;
    animation.duration = 0.5f * 0.68;
    animation.timingFunction = UIViewAnimationCurveEaseInOut;
	animation.fillMode = kCAFillModeForwards;
	animation.endProgress = 0.68;
	animation.removedOnCompletion = NO;
    animation.type = @"pageCurl";
    [self.view exchangeSubviewAtIndex:0 withSubviewAtIndex:1];
    [self.view.layer addAnimation:animation forKey:@"startAnimation"];
   
    
    settingController.view.hidden = NO;
    dataView.hidden = YES;
	self.lastAnimation = animation;
    for (int i = 0; i < [self.dataView.subviews count]; i++) {
        UIView *view = [self.dataView.subviews objectAtIndex:i];
        [view setUserInteractionEnabled:NO];    
    }

    isHalfAnimation = YES;
}

-(void)commitAnimation{
    if (isHalfAnimation) {
		self.lastAnimation.startProgress = 0.32;
        self.lastAnimation.type = @"pageUnCurl";
		self.lastAnimation.fillMode = kCAFillModeRemoved;
		[self.view.layer removeAnimationForKey:@"startAnimation"];
        [self.view.layer addAnimation:self.lastAnimation forKey:@"startAnimation"];
        [self.view exchangeSubviewAtIndex:0 withSubviewAtIndex:1];
        
		isHalfAnimation = NO;
        settingController.view.hidden = YES;
        dataView.hidden = NO;
        for (int i = 0; i < [self.dataView.subviews count]; i++) {
			UIView *view = [self.dataView.subviews objectAtIndex:i];
            [view setUserInteractionEnabled:YES]; 
		}
        
        if (lastSearchType != settingController.searchType) {
            lastSearchType = settingController.searchType;
            self.searchMode = settingController.searchType;
            [self loadData:-1];
        }
        
        if (lastDisplayType != settingController.displayType) {
            lastDisplayType =settingController.displayType;
            [self loadData:-1];
        }
	}    
}

- (void)curlUp{
    
     NSLog(@"Curl");
    
     // Curl the image up or down
    CATransition *animation = [CATransition animation];
    [animation setDelegate:self];
    [animation setDuration:0.35];
    [animation setTimingFunction:UIViewAnimationCurveEaseInOut];
     if (!isHalfAnimation){
         animation.type = @"pageCurl";
         animation.fillMode = kCAFillModeForwards;
         animation.endProgress = 0.58;
     } 
     else {
            animation.type = @"pageUnCurl";
            animation.fillMode = kCAFillModeBackwards;
            animation.startProgress = 0.42;
            
    }
    
    [animation setRemovedOnCompletion:NO];
    [self.view exchangeSubviewAtIndex:0 withSubviewAtIndex:1];
    [self.dataView.layer addAnimation:animation forKey:@"pageCurlAnimation"];
    
     // Disable user interaction where necessary
     if (!isHalfAnimation) {         
     } 
     else{
     }
     
    isHalfAnimation = !isHalfAnimation;
}

-(void)setTitleText:(NSString *)text {

    int tody,thisMonth,thisYear;
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *dateComponents = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:[NSDate new]];
    thisYear = [dateComponents year];
    thisMonth = [dateComponents month];
    tody = [dateComponents day];
    [calendar release];
    
    NSString *title= @"";
    switch (searchMode) {
        case 0:
            title = [NSString stringWithFormat:@"%04d-%02d-%02d",thisYear,thisMonth,tody];
            if ([text isEqualToString:title]) {
                text = [text stringByAppendingString:@"(今天)"];
            }
            break;
        case 1:
            title = [NSString stringWithFormat:@"%04d-%02d",thisYear,thisMonth];
            if ([text isEqualToString:title]) {
                text = [text stringByAppendingString:@"(本月)"];
            }
            break;
        case 2:
            title = [NSString stringWithFormat:@"%04d",thisYear];
            if ([text isEqualToString:title]) {
                text = [text stringByAppendingString:@"(今年)"];
            }
            break;
        default:
            break;
    }
    
    self.title = text;
}

@end
